package com.int_tech.station.controller;

import com.int_tech.car.dao.CarDao;
import com.int_tech.car.entity.Car;
import com.int_tech.control.controller.TestLocationToBaidu;
import com.int_tech.mession.dao.MessionDao;
import com.int_tech.mession.entity.Mession;
import com.int_tech.messionLog.dao.MessionLogDao;
import com.int_tech.messionLog.entity.MessionLog;
import com.int_tech.rate.controller.RateController;
import com.int_tech.station.dao.StationDao;
import com.int_tech.station.entity.CarLocationOnTheWay;
import com.int_tech.station.entity.Station;
import com.int_tech.station.service.StationService;
import com.int_tech.user.dao.ClientDao;
import com.int_tech.user.dao.UserDao;
import com.int_tech.user.entity.Client;
import com.int_tech.user.entity.User;
import com.int_tech.utils.*;
import com.int_tech.utils.poi.Amount;
import com.int_tech.utils.poi.ReadExcelCarCeiling;
import com.int_tech.utils.poi.ReadExcelStation;
import com.int_tech.utils.poi.ReadExcelStationCeiling;
import com.int_tech.utils.poiOut.StationPoi;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.smartcardio.Card;
import java.io.*;
import java.net.UnknownHostException;
import java.util.*;

@Controller
@RequestMapping("station")
public class StationController {


    @Autowired
    private StationService stationService;

    @Autowired
    private UserDao userDao;

    @Autowired
    private MessionDao messionDao;

    @Autowired
    private CarDao carDao;

    @Autowired
    private MessionLogDao messionLogDao;

    @Autowired
    private ClientDao clientDao;

    @Autowired
    private StationDao stationDao;

    Map<String,CarLocationOnTheWay> baiduMap = new HashMap<>();

    Map<String,CarLocationOnTheWay> allBaiduMap = new HashMap<>();



    @RequestMapping(value = "/updateNewArea", method = RequestMethod.GET)
    public void updateNewArea(Model model, HttpServletRequest request) throws IOException {

        List<Station> stations = stationDao.findAll();

        for(Station station : stations)
        {
            if(station.getArea().contains("&"))
            {

            }
            else
            {
                String area = TestLocationToBaidu.map_tx2bd(Double.parseDouble(station.getArea().split(",")[0]),Double.parseDouble(station.getArea().split(",")[1]));
                station.setArea(area);
                station.setUpdateTime(new Date());

                stationDao.save(station);
            }
        }
    }

    /**
     * 修改场站坐标
     * @param model
     * @param request
     * @throws IOException
     */
    @RequestMapping(value = "/updateArea", method = RequestMethod.GET)
    public void updateArea(Model model, HttpServletRequest request) throws IOException {

        List<Station> stations = stationDao.findByArea(null);

        for(Station station : stations)
        {
            String area = getPoint(station.getAddress());
            station.setArea(area);
            station.setUpdateTime(new Date());

            stationDao.save(station);
        }
    }


    /**
     * 导入场站
     * @param model
     * @param request
     */
    @RequestMapping(value = "/exportStations", method = RequestMethod.GET)
    public void exportStations(Model model, HttpServletRequest request) throws IOException {

        File excelFile = new File("F:\\222222.xls");
        HSSFWorkbook wb = new HSSFWorkbook(new FileInputStream(excelFile));
        HSSFSheet sheet = wb.getSheetAt(0);

        int m = 0;
        int n = 0;
        try
        {
            for (Row row : sheet) {
                m++;
                if(m == 1)
                {
                    continue;
                }

                Station station = new Station();
                String sss = "";
                for (Cell cell : row) {

                    n++;

                    if(n == 2)
                    {
//                    System.out.print("场站名称："+cell.getStringCellValue().toString());
                        station.setName(cell.getStringCellValue().toString());
                    }

                    if(n == 4)
                    {
//                    System.out.print("省市县："+cell.getStringCellValue().toString().replaceAll("-",""));
                        cell.setCellType(Cell.CELL_TYPE_STRING);
                        sss = cell.getStringCellValue().toString()+sss;
                    }

                    if(n == 3)
                    {
//                    System.out.print("具体地址："+cell.getStringCellValue().toString());
                        cell.setCellType(Cell.CELL_TYPE_STRING);
                        sss = ","+cell.getStringCellValue().toString();
                    }
                }

                station.setCreateTime(new Date());
                station.setClientId(26);
                station.setClentName("京东");
                station.setArea(sss);


                stationDao.save(station);

                n = 0;
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    /**
     * 场站管理，根据id场站信息
     */
    @RequestMapping(value = "/ByIdStation", method = RequestMethod.GET)
    public String AllStation(Model model, HttpServletRequest request) {
        int clientId = (int) request.getSession().getAttribute("uid");
        User user = userDao.findOne(clientId);
        if (user.getType() == 1) {
            List<Station> stationList = (List<Station>) stationService.findAllStation().getData();
            List<Station> list = AreaUtils.areaHelp(stationList);
            model.addAttribute("allStations", list);
            return "/station/station";
        }
        List<Station> stationList = (List<Station>) stationService.findStationByClientId(clientId).getData();
        List<Station> list = AreaUtils.areaHelp(stationList);
        model.addAttribute("allStations", list);
        model.addAttribute("allStations", list);
        return "/station/station";
    }


    /**
     * 场站管理，添加场站信息
     */
    @RequestMapping(value = "/addStation", method = RequestMethod.POST)
    @ResponseBody
    public String addStation(Station station, HttpServletRequest request) {
        String json = "";
        int clientId = (int) request.getSession().getAttribute("uid");
        station.setClientId(clientId);

        //所属客户名称
        User user = userDao.findById(clientId);

        Client client = clientDao.findClientById(Integer.parseInt(user.getClientId()));

        String area = station.getArea();
        String s = AreaUtils.areaHelps(area);
        station.setArea(s);
        station.setCreateTime(new Date());
        station.setUpdateTime(new Date());
        station.setClentName(client.getName());
        Station save = stationDao.save(station);
        String a = "";
        if (save != null) {
            a = "0";
        } else {
            a = "1";
        }
        return a;
    }


    /**
     * 场站管理，删除场站信息
     */
    @RequestMapping(value = "/deleteStation", method = RequestMethod.POST)
    @ResponseBody
    public Result deleteStation(String order, HttpServletRequest request) {
        int clientId = (int) request.getSession().getAttribute("uid");
        User user = userDao.findOne(clientId);
        if (user.getType() == 1) {
            return Result.build(500, "当前用户没有该权限");
        }
        Integer id = Integer.valueOf(order);
        Result result = stationService.deleteStationByid(id);
        return result;
    }


    /**
     * 场站管理，修改场站信息
     */
    @RequestMapping(value = "/updateStation", method = RequestMethod.POST)
    @ResponseBody
    public Result updateStation(Station station, HttpServletRequest request) {
        int clientId = (int) request.getSession().getAttribute("uid");

        //所属客户名称
        User user = userDao.findById(clientId);

        Client client = clientDao.findClientById(Integer.parseInt(user.getClientId()));

        station.setClentName(client.getName());
        station.setClientId(clientId);
        String area = station.getArea();
        String s = AreaUtils.areaHelps(area);
        station.setArea(s);
        Result result = stationService.updateStation(station);
        return result;
    }

    /**
     * 通过文字模糊查询场站信息
     * @param request
     * @return
     * @throws UnsupportedEncodingException
     * @throws UnknownHostException
     */
    @RequestMapping(value = "/getStationByKey", method=RequestMethod.POST,produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String getStationByKey(HttpServletRequest request) throws UnsupportedEncodingException, UnknownHostException {

        int clientId = (int) request.getSession().getAttribute("uid");

        List<Car> carList = carDao.findCarByIsDel(0);

        String text = request.getParameter("text");
        if(text.contains("物流")||text.contains("快")||text.contains("京东")||text.contains("生鲜")||text.contains("华南"))
        {
            System.out.print(111);
        }

        List<Station> stationList = new ArrayList<>();

        List<Station> stations = new ArrayList<>();

        //通过关键字或者场站id查询
        if(clientId == 1)
        {
            if(StringUtils.isEmpty(text))
            {
                stationList = stationDao.findAll();
                for (Station station : stationList)
                {
                    int count = 0;
                    for (Car car : carList)
                    {
                        if(station.getId() == car.getStationId())
                        {
                            count ++;
                        }
                    }

                    if(count > 0)
                    {
                        station.setCarCount(count);
                        stations.add(station);
                    }

                }

//                stations.addAll(stationList);
            }
            else
            {
                stationList = stationDao.findAll();
                for (Station station : stationList)
                {
                    if(station.getName().contains(text))
                    {
                        int count = 0;
                        for (Car car : carList)
                        {
                            if(station.getId() == car.getStationId())
                            {
                                count ++;
                            }
                        }
                        if(count > 0)
                        {
                            station.setCarCount(count);
                            stations.add(station);
                        }
                    }
                }
            }
        }
        else
        {
            if(StringUtils.isEmpty(text))
            {
                stationList = stationDao.findByClientId(clientId);
                for (Station station : stationList)
                {
                    int count = 0;
                    for (Car car : carList)
                    {
                        if(station.getId() == car.getStationId())
                        {
                            count ++;
                        }
                    }
                    if(count > 0)
                    {
                        station.setCarCount(count);
                        stations.add(station);
                    }
                }
//                stations.addAll(stationList);
            }
            else
            {
                stationList = stationDao.findByClientId(clientId);
                for (Station station : stationList)
                {
                    if(station.getName().contains(text))
                    {
                        int count = 0;
                        for (Car car : carList)
                        {
                            if(station.getId() == car.getStationId())
                            {
                                count ++;
                            }
                        }
                        if(count > 0)
                        {
                            station.setCarCount(count);
                            stations.add(station);
                        }
                    }
                }
            }
        }

        JSONObject object = new JSONObject();
        if(stations.size() == 0)
        {
            object.put("status", "success");
            object.put("stationList", "");
        }
        else
        {
            object.put("status", "success");
            String str = "";
            for (Station station:stations) {
                str += "<li class='p-bt-10 b-botom pos-re'>";
                str += "<a href='javascript:void(0);' title='"+station.getName()+"（"+ station.getCarCount()+"辆）'>";
                str += "<span class='txt-limit getCars'' name='"+station.getId()+"'>"+station.getName()+"（"+station.getCarCount()+"辆）</span>";
                str += "</a>";
                str += "<span class='txt-num'></span>";
                str += "<ul class='carListNumbers'>";
                str += "</ul></li>";
            }


//            JSONArray jsonArray = JSONArray.fromObject(stations);
            object.put("stationList", str);
        }

        return object.toString();
    }

    /**
     * 通过车牌号反向定位车辆信息，展示列表
     * @param request
     * @return
     * @throws UnsupportedEncodingException
     * @throws UnknownHostException
     */
    @RequestMapping(value = "/getStationAndCarByCarNumber", method=RequestMethod.POST,produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String getStationAndCarByCarNumber(HttpServletRequest request) throws UnsupportedEncodingException, UnknownHostException {

//        int clientId = (int) request.getSession().getAttribute("uid");

        String text = request.getParameter("carNumber");

        Car car = carDao.findCarByCarNumberAndIsDel(text,0);

        Station station = stationDao.findById(car.getStationId());
        int count = carDao.countByStationId(station.getId());
        station.setCarCount(count);

        List<Car> cars = carDao.findCarByStationIdAndIsDel(station.getId(),0);

        String str = "";
        str += "<li class='p-bt-10 b-botom pos-re'>";
        str += "<a href='javascript:void(0);' title='"+station.getName()+"（"+ station.getCarCount()+"辆）'>";
        str += "<span class='txt-limit getCars'' name='"+station.getId()+"'>"+station.getName()+"（"+station.getCarCount()+"辆）</span>";
        str += "</a>";
        str += "<span class='txt-num'></span>";
        str += "<ul class='carListNumbers'>";
        for (Car car1 : cars)
        {
            str += "<li class=' p-bt-10 "+car.getCarNumber()+"'>"+car.getCarNumber()+"</li>";
        }
        str += "</ul></li>";


        JSONObject object = new JSONObject();
        object.put("resultList", str);

        return object.toString();
    }



    /**
     * 通过场站id获取场站坐标
     * @param request
     * @return
     * @throws UnsupportedEncodingException
     * @throws UnknownHostException
     */
    @RequestMapping(value = "/getStationById", method=RequestMethod.POST,produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String getStationById(HttpServletRequest request) throws UnsupportedEncodingException, UnknownHostException {


        String stationId = request.getParameter("stationId");

        request.getSession().setAttribute("stationId",stationId);

        Station station = stationDao.findById(Integer.valueOf(stationId));

        JSONObject object = new JSONObject();

        object.put("station",station);

        String area1 = station.getArea().split("&")[0].split(",")[0];
        String area2 = station.getArea().split("&")[0].split(",")[1];
        String area3 = station.getArea().split("&")[1].split(",")[0];
        String area4 = station.getArea().split("&")[1].split(",")[1];
        String area5 = station.getArea().split("&")[2].split(",")[0];
        String area6 = station.getArea().split("&")[2].split(",")[1];
        String area7 = station.getArea().split("&")[3].split(",")[0];
        String area8 = station.getArea().split("&")[3].split(",")[1];

        object.put("point1",area1);
        object.put("point2",area2);
        object.put("point3",area3);
        object.put("point4",area4);
        object.put("point5",area5);
        object.put("point6",area6);
        object.put("point7",area7);
        object.put("point8",area8);



        return object.toString();
    }

    /**
     * 定时获取车辆最后出现位置
     * @param request
     * @return
     * @throws UnsupportedEncodingException
     * @throws UnknownHostException
     */
    @RequestMapping(value = "/getCarLastShow", method=RequestMethod.GET,produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String getCarLastShow(HttpServletRequest request,String carNumber) throws UnsupportedEncodingException, UnknownHostException {

        List<MessionLog> messionLog = messionLogDao.findByCarNumber(carNumber);

        MessionLog log = messionLog.get(0);

        JSONObject object = new JSONObject();
        object.put("lat",log.getLat());
        object.put("lng",log.getLng());

        return object.toString();


    }




    /**
     * 定时更新在途车辆地图
     * @param request
     * @return
     * @throws UnsupportedEncodingException
     * @throws UnknownHostException
     */
    @RequestMapping(value = "/getTaskByClientId", method=RequestMethod.GET,produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String getTaskByClientId(HttpServletRequest request) throws UnsupportedEncodingException, UnknownHostException {

        long s1 = System.currentTimeMillis();
        String clientId = (String)request.getSession().getAttribute("clientId");

//        Long clientId = (Long) request.getSession().getAttribute("clientId");

//        Long stationId = (Long) request.getSession().getAttribute("stationId");

        String stationId = (String) request.getSession().getAttribute("stationId");

        String clickStation = request.getParameter("clickStation");

//        List<Mession> messionList = messionDao.findByIsOver(0);

        baiduMap = new HashMap<>();

        allBaiduMap = new HashMap<>();


        //所有车辆
        List<CarLocationOnTheWay> result111 = new ArrayList<>();

        String mapKey = "";

        if(stationId == null)
        {
            mapKey = "clientId_"+clientId;
        }
        else
        {
            mapKey = "clientId_"+clientId+"*stationId_"+stationId;
        }


        List<CarLocationOnTheWay> result = likeString(mapKey, baiduMap);

        if("1".equals(clientId))
        {
            result = result111;
        }

        JSONArray jsonArray = JSONArray.fromObject(result);


        JSONObject jsonObject = new JSONObject();

        jsonObject.put("carList",jsonArray.toString());


        //每辆车最后一条数据
        long s4 = System.currentTimeMillis();
        List<MessionLog> messionLogList = messionLogDao.findLogGroupByCarNumber();
        long s5 = System.currentTimeMillis();
        System.out.print("查数据日志用时" + (s5 - s4) + "ms");

        long s2 = System.currentTimeMillis();
        System.out.print("查数据用时" + (s2 - s1) + "ms");

        //查询每组车辆最后一条数据
        //所有车辆
        List<CarLocationOnTheWay> result222 = new ArrayList<>();

        //所有车辆
        List<Car> cars = carDao.findCarByIsDel(0);

        for (MessionLog messionLog : messionLogList)
        {
            try
            {
                Car car = new Car();

                for (Car car1 : cars)
                {
                    if(messionLog.getCarNumber().equals(car1.getCarNumber()))
                    {
                        car = car1;
                        break;
                    }
                }

                if(car == null)
                {
                    continue;
                }
                String today = DateTool.Date2String(new Date(),"yyyy-MM-dd");

                String resultssss = RateController.getFirstAndLastOfWeek(today);
                String startTime = resultssss.split("=")[0] + " 00:00:00";

//                startTime = "2018-06-01 00:00:00";
                Date sTime = DateTool.string2Date(startTime,"yyyy-MM-dd HH:mm:ss");

//                List<MessionLog> messionLogList1 = messionLogDao.findFirstByCarNumberAndCreateTimeOrderByCreateTimeDesc(messionLog.getCarNumber(),sTime);

                CarLocationOnTheWay carLocationOnTheWay = new CarLocationOnTheWay();

                carLocationOnTheWay.setXLocation(messionLog.getLat());
                carLocationOnTheWay.setYLocation(messionLog.getLng());
                carLocationOnTheWay.setStationName(car.getStationName());
                carLocationOnTheWay.setCarNumber(car.getCarNumber());
                carLocationOnTheWay.setDataTime(messionLog.getCreateTime());

                if("1".equals(clickStation))
                {
                    if(String.valueOf(car.getStationId()).equals(stationId))
                    {
                        allBaiduMap.put("clientId_"+String.valueOf(car.getClientId())+"*stationId_"+String.valueOf(car.getStationId())+"*carNumber_"+car.getCarNumber(),carLocationOnTheWay);

                        if(String.valueOf(car.getClientId()).equals(clientId))
                        {
                            result222.add(carLocationOnTheWay);
                        }
                        else
                        {
                            User user = userDao.findById(Integer.parseInt(clientId));

                            if(String.valueOf(car.getClientId()).equals(user.getClientId()))
                            {
                                result222.add(carLocationOnTheWay);
                            }
                        }
                    }
                }
                else
                {
                    allBaiduMap.put("clientId_"+String.valueOf(car.getClientId())+"*stationId_"+String.valueOf(car.getStationId())+"*carNumber_"+car.getCarNumber(),carLocationOnTheWay);

                    if(String.valueOf(car.getClientId()).equals(clientId))
                    {
                        result222.add(carLocationOnTheWay);
                    }

                }
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }

        }

        List<CarLocationOnTheWay> carLocationOnTheWays = new ArrayList<>();

        Map map = new HashMap();
        //遍历过滤不对的
        for (CarLocationOnTheWay carLocationOnTheWay : result222)
        {
            CarLocationOnTheWay value = (CarLocationOnTheWay) map.get(carLocationOnTheWay.getCarNumber());

            if(value == null)
            {
                map.put(carLocationOnTheWay.getCarNumber(),carLocationOnTheWay);
                carLocationOnTheWays.add(carLocationOnTheWay);
            }
            else
            {
                if(value.getDataTime().after(carLocationOnTheWay.getDataTime()))
                {

                }
                else
                {
                    carLocationOnTheWays.remove(value);
                    carLocationOnTheWays.add(carLocationOnTheWay);
                    map.put(carLocationOnTheWay.getCarNumber(),carLocationOnTheWay);
                }
            }
        }


        JSONArray jsonArray2 = JSONArray.fromObject(carLocationOnTheWays);


        jsonObject.put("allCarList",jsonArray2.toString());


        long s3 = System.currentTimeMillis();
        System.out.print("获取文件名用时" + (s2 - s1) + "ms");
        System.out.print("获取文件名用时" + (s3 - s2) + "ms");

        return jsonObject.toString();
    }


    public static List<CarLocationOnTheWay> likeString(String key, Map<String, CarLocationOnTheWay> map) {
        List<CarLocationOnTheWay> list = new ArrayList<CarLocationOnTheWay>();
        Iterator it = map.entrySet().iterator();
        while(it.hasNext()) {
            Map.Entry<String, CarLocationOnTheWay> entry = (Map.Entry<String, CarLocationOnTheWay>)it.next();
            if (entry.getKey().indexOf(key) != -1) {
                list.add(entry.getValue());
            }
        }
        return list;
    }

    /**
     * 场站管理，搜索场站
     */
    @RequestMapping(value = "/souSuoStation")
    public String souSuoStation(Model model, HttpServletRequest request, String word) {
        int clientId = (int) request.getSession().getAttribute("uid");
        User user = userDao.findOne(clientId);
        List<Station> ssStation = new ArrayList<>();
        if (user.getType() == 1) {
            List<Station> list = (List<Station>) stationService.findAllStation().getData();
            for (Station ls : list) {
                String ss = ls.getArea().substring(0, ls.getArea().indexOf("&"));
                ls.setArea(ss);
                String obj = ls.toString();
                if (obj.contains(word)) {
                    ssStation.add(ls);
                }
            }
        }
        model.addAttribute("allStations", ssStation);
        return "/station/station";
    }

    /**
     * TODO 分页
     *
     * @param page 页数
     * @param size 条数
     * @return
     * @author dmy
     */
    @GetMapping("getStation")
    public String getCars(@RequestParam(value = "page", defaultValue = "1") Integer page,
                          @RequestParam(value = "size", defaultValue = "10") Integer size,
                          Model model, HttpServletRequest request) {
//        int clientId = (int) request.getSession().getAttribute("uid");
        int clientId = -99;

        try
        {
            clientId = (int) request.getSession().getAttribute("uid");
        }
        catch (Exception e)
        {
            return "car/retry";
        }
        User user = userDao.findOne(clientId);
        PageRequest pageRequest = new PageRequest(page - 1, size);
        Page<Station> stationPage = null;
        //超级管理员
        if (user.getType() == 1) {
            stationPage = stationService.getCarByPageable(pageRequest);
        } else {
            stationPage = stationService.getCarByPageable(pageRequest, clientId);
        }
        List<Station> stationList = stationPage.getContent();
        List<Station> list = AreaUtils.areaHelp(stationList);
        model.addAttribute("word", "");
        model.addAttribute("type", "1");
        model.addAttribute("allStations", list);
        model.addAttribute("currentPage", page);
        model.addAttribute("size", size);
        model.addAttribute("maxSize", stationPage.getTotalPages());

        List<Client> clients = clientDao.findById(Integer.parseInt(user.getClientId()));

        model.addAttribute("clients",clients);

        return "/station/station";
    }

    /**
     * TODO 模糊分页
     *
     * @param page 页数
     * @param size 条数
     * @return
     * @author dmy
     */
    @RequestMapping("choose")
    public String choose(@RequestParam(value = "page", defaultValue = "1") Integer page,
                         @RequestParam(value = "size", defaultValue = "10") Integer size,
                         @RequestParam(value = "word") String word, Model model, HttpServletRequest request) {
        int clientId = (int) request.getSession().getAttribute("uid");
        User user = userDao.findOne(clientId);
        List<Station> stationList = null;
        //超级管理员
        if (user.getType() == 1) {
            stationList = (List<Station>) stationService.findAllStation().getData();
        } else {
            stationList = (List<Station>) stationService.findStationByClientId(clientId).getData();
        }
        List<Station> stationWordList = new ArrayList<>();
        for (Station ca : stationList) {
            if (ca.toString().contains(word)) {
                stationWordList.add(ca);
            }
        }
        int ceil = (int) Math.ceil(stationWordList.size() / 10);

        List<Station> listStation = AreaUtils.areaHelp(stationWordList);
        List<Station> list = WordListUtils.wordListUtils(size, page, listStation);
        model.addAttribute("word", word);
        model.addAttribute("allStations", list);
        model.addAttribute("currentPage", page);
        model.addAttribute("size", size);
        model.addAttribute("maxSize", ceil + 1);
        model.addAttribute("type", "2");

        List<Client> clients = clientDao.findById(Integer.parseInt(user.getClientId()));

        model.addAttribute("clients",clients);
        return "/station/station";
    }


    /**
     * TODO ex导出
     *
     * @param
     * @return
     * @author dmy
     */
    @RequestMapping("exout")
    public void exOut(HttpServletResponse response, @RequestParam(value = "word") String word, HttpServletRequest request) {
        int clientId = (int) request.getSession().getAttribute("uid");
        User user = userDao.findOne(clientId);
        List<Station> stationList = null;
        List<Station> list = new ArrayList<>();
        if (word == ""&&word==null) {
            list = (List<Station>) stationService.findStationByClientId(clientId).getData();
        } else {
            if (user.getType() == 1) {
                stationList = (List<Station>) stationService.findAllStation().getData();
            } else {
                stationList = (List<Station>) stationService.findStationByClientId(clientId).getData();
            }
            for (Station station : stationList) {
                if (station.toString().contains(word)) {
                    list.add(station);
                }
            }
        }
        StationPoi.stationPoi(list, response);
    }

    /**
     * TODO ex导入2
     *
     * @param
     * @return
     * @author dmy
     */
    @PostMapping("exoutIn")
    @ResponseBody
    public Result exoutIn(@RequestParam("fileName") MultipartFile file, HttpServletRequest request) {
        int clientId = (int) request.getSession().getAttribute("uid");
        try {
            // 获取文件名
            String fileName = file.getOriginalFilename();
//        logger.info("上传的文件名为：" + fileName);
            // 获取文件的后缀名
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            List<Station> list = new ArrayList<>();
            if (suffixName.equals(".xls")) {
                list = ReadExcelStation.readExcel(file);
            } else if (suffixName.equals(".xlsx")) {
                list = ReadExcelStationCeiling.readExcel(file);
            } else {
                return Result.build(201, "文件格式不正确");
            }

            int i = 0;
            for (Station station : list) {
                station.setClientId(clientId);
                station.setCreateTime(new Date());
                station.setUpdateTime(new Date());
                stationDao.save(station);
                i=i+1;
            }
            return Result.build(200,"导入总条数："+list.size()+"；"+"成功条数："+i+"。");
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
            return Result.build(500,"系统异常");
        }
    }


    public static String getPoint(String area2) {
        try {
            String sCurrentLine;
            String sTotalString;
            sCurrentLine = "";
            sTotalString = "";
            java.io.InputStream l_urlStream;

            String area = "";

            String urlsss = "http://api.map.baidu.com/geocoder/v2/?address=" + area2 + "&output=json&ak=TsCP2qXsP0RLmchQ7cQYyQa1C5Cwh4er&callback=showLocation";
            urlsss = urlsss.replaceAll("\r|\n", "");

            java.net.URL l_url = new java.net.URL(urlsss);

            java.net.HttpURLConnection l_connection = (java.net.HttpURLConnection) l_url.openConnection();
            l_connection.connect();
            l_urlStream = l_connection.getInputStream();
            java.io.BufferedReader l_reader = new java.io.BufferedReader(new java.io.InputStreamReader(l_urlStream));
            String str = l_reader.readLine();
            //用经度分割返回的网页代码
            String s = "," + "\"" + "lat" + "\"" + ":";
            String strs[] = str.split(s, 2);
            String s1 = "\"" + "lng" + "\"" + ":";
            String a[] = strs[0].split(s1, 2);
//            System.out.println(a[1]);
//            System.out.print(Float.parseFloat(a[1]));
            area += String.valueOf(Float.parseFloat(a[1]));
            s1 = "}" + "," + "\"";
            String a1[] = strs[1].split(s1, 2);
//            System.out.println(a1[0]);
//            System.out.print(Float.parseFloat(a1[0]));
            area += ","+String.valueOf(Float.parseFloat(a1[0]));
            return area;
            //shop.setLat(a1[0]);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
